<template>
  <!-- 投注 -->
  <div class="transactions">
    <div class="header-mine-search">
      <div class="header-mine-search__line">
        <div class="header-mine-search__list">
          <div class="search__list-label">{{t('Popularize.Time')}}：</div>
          <div class="search__list-wrapper small-wrapper">
            <el-select v-model="form.timeType" clearable size="small">
              <el-option
                v-for="item in getEnumOptions('bettingRecordTimeType')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <div class="search__list-wrapper search-timer">
            <el-date-picker
              v-model="form.date"
              type="daterange"
              unlink-panels
              range-separator="-"
              :start-placeholder="t('lang.el.datepicker.startDate')"
              :end-placeholder="t('lang.el.datepicker.endDate')"
              :shortcuts="shortcuts"
              value-format="YYYY-MM-DD"
              :clearable="false"
              size="large"
            />
          </div>
          <div class="search__list-label">{{t('UserInfo.Currency')}}：</div>
          <div class="search__list-wrapper small-wrapper">
            <el-select v-model="form.currencyId" clearable size="small">
              <el-option
                v-for="item in piniaUserinfo.getWallet"
                :key="item.currencyId"
                :label="item.currencyName"
                :value="item.currencyId"
              />
            </el-select>
          </div>
          <el-button type="primary" class="header-mine-search__btns search-margin" @click="getUserBetInfo" :loading="btnLoading">{{t('BetRecord.Search')}}</el-button>
        </div>
        <div class="header-mine-search__list">
          <el-button type="primary" class="header-mine-search__btns search-margin" @click="openSelector">{{t('BetRecord.Select')}}</el-button>
        </div>
      </div>
      <div class="header-mine-search__line">
        <div class="header-mine-search__list">
          <div class="search__list-label"></div>
          <div class="search__list-wrapper small-wrapper">
            <el-checkbox v-model="form.isBet" :label="t('BetRecord.ViewBets')" />
          </div>
        </div>
        <div class="header-mine-search__list">
          <div class="search__list-label">{{t('Transaction.status')}}：</div>
          <div class="search__list-wrapper small-wrapper">
            <el-select v-model="form.status" clearable size="small">
              <el-option
                v-for="item in getEnumOptions('bettingRecordStatus')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </div>
      </div>
    </div>
    <div class="dialog-content">
      <div class="dialog-content-box">
        <div class="dialog-content-wrapper">
          <el-table :data="capitalRecord" height="100%" class="record-table" :empty-text="t('BetRecord.Nocontent')">
            <el-table-column align="center" prop="gameType" :label="t('BetRecord.GameType')">
              <template #default="{row}">
                {{ t(getEnumValue('gamesType', `${row.gameType}`)) }}
              </template>
            </el-table-column>
            <el-table-column align="center" prop="gameName" :label="t('BetRecord.GameName')"/>
            <el-table-column align="center" prop="currencyName" :label="t('BetRecord.CurrencyName')"/>
            <el-table-column align="center" prop="orderId" :label="t('BetRecord.NoteNumber')"/>
            <el-table-column align="center" prop="betTime" :label="t('BetRecord.BettingTime')">
              <template #default="{row}">
                {{ parseTime(row.betTime) }}
              </template>
            </el-table-column>
            <el-table-column align="center" prop="payOutTime" :label="t('BetRecord.PayoutTime')">
              <template #default="{row}">
                {{ parseTime(row.payOutTime) }}
              </template>
            </el-table-column>
            <el-table-column align="center" prop="betMoney" :label="t('BetRecord.BetAmount')">
              <template #default="{row}">
                {{ Math.abs(row.betMoney).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column align="center" prop="validBetMoney" :label="t('BetRecord.EffectiveBet')">
              <template #default="{row}">
                {{ Math.abs(row.validBetMoney).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column align="center" prop="winMoney" :label="t('BetRecord.Payout')">
              <template #default="{row}">
                {{ Number(row.winMoney).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column align="center" prop="status" :label="t('BetRecord.Status')">
              <template #default="{row}">
                {{ t(getEnumValue('bettingsType', `${row.status}`)) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <div class="record-pagination">
      <ZPagination
        v-model:pagination="pagination"
        :query="getUserBetInfo"
      />
    </div>
  </div>
  <Dialog
    v-model:visible="dialogConfig.show"
    v-model:title="dialogConfig.title"
    :width="dialogConfig.width"
    v-model:autoHeight="dialogConfig.autoHeight"
    :headerFixed="dialogConfig.headerFixed"
  >
    <div class="games-type-selector">
      <div class="games-type-selector-header">
        <el-checkbox v-model="form.all" :label="t('BetRecord.All')" @change="handleToggleAll"/>
        <el-checkbox v-model="form.reverse" :label="t('BetRecord.ReverseSelection')" @change="handleToggleReverse"/>
      </div>
      <div class="games-type-selector-main">
        <div class="games-type-selector-list" v-for="item in gameTypeAndChannel" :key="item.type">
          <div class="games-type-selector-list__left">
            <el-checkbox-group v-model="item.checked" @change="handleChecked($event, 'item', item)">
              <el-checkbox :label="item.type">{{ t(getEnumValue('gamesType', `${item.type}`)) }}</el-checkbox>
            </el-checkbox-group>
          </div>
          <div class="games-type-selector-list__right">
            <el-checkbox-group v-model="item.nextChecked" @change="handleChecked($event, 'next', item)">
              <el-checkbox :label="next.type"  v-for="next in item.next" :key="next.type">{{ next.typeName }}</el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </div>
      <el-button type="primary" class="games-type-selector-btn" @click="getCurrentGameTypeSelected">{{t('BetRecord.Sure')}}</el-button>
    </div>
  </Dialog>
</template>

<script setup lang="ts" name="BettingRecord">
import recordApi from '@/api/modules/record';
import userinfo from '@/store/userinfo';
import { parseTime } from '@/utils/format';
import { getEnumValue, getEnumOptions } from '@/utils/enums';

const piniaUserinfo:any = userinfo();


const { t } = useI18n();
const data:any = reactive({
  dialogConfig: {
    show: false,
    type: '',
    title: "",
    headerFixed: false,
    width: 600,
    autoHeight: false
  },
  form: {
    timeType: "1",
    status: "3",
    isBet: false,
    currencyId: piniaUserinfo.getCurrentWallet.currencyId,
    date: [
      parseTime(new Date().getTime() - 3600 * 1000 * 24 * 7),
      parseTime(new Date())
    ]
  },
  capitalRecord: [], // 资金记录
  pagination: {
    total: 0,
    pageSize: 10,
    pageNum: 1
  },
  gameTypeAndChannel: [],
  btnLoading: false,
});

const {
  dialogConfig,
  form,
  capitalRecord,
  pagination,
  gameTypeAndChannel,
  btnLoading,
} = toRefs(data);

const shortcuts = [
  {
    text: t('lang.el.datepicker.lastweek'),
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: t('lang.el.datepicker.prevMonth'),
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: t('lang.el.datepicker.prevMonth3'),
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

const getUserBetInfo = () => {
  btnLoading.value = true;
  recordApi.getUserBetInfo({
    currencyId: form.value.currencyId,
    gameChannel: form.value.gameChannel || "",
    gameType: form.value.gameType || "",
    isBet: form.value.isBet ? 1 : 0,
    pageNum: pagination.value.pageNum,
    pageSize: pagination.value.pageSize,
    startTime: form.value.date[0],
    endTime: form.value.date[1],
    status: form.value.status,
    timeType: form.value.timeType,
    userId: Number(piniaUserinfo.getUserinfo.user.id),
  }).then((response:any)=>{
    console.log("投注记录", response)
    if(response.code === 200){
      capitalRecord.value = response.rows;
      pagination.value.total = response.total;
    }
  }).finally(()=>{
    btnLoading.value = false;
  });
}
getUserBetInfo();

// 所有游戏类型
const getGameTypeAndChannel = () => {
  recordApi.getGameTypeAndChannel({}).then((response:any)=>{
    console.log(response)
    if(response.code === 200){
      gameTypeAndChannel.value = response.data || [];
      gameTypeAndChannel.value.forEach((element: any) => {
        element.checked = [element.type];
        element.nextChecked = element.next.map((im:any)=>im.type);
      });
      form.value['all'] = true;
    }
  });
}
getGameTypeAndChannel();

// 全选
const handleToggleAll = (val:any) => {
  if(val === 'cancelAll'){
    form.value.all = false;
  }else{
    if(val){
      gameTypeAndChannel.value.forEach((element: any) => {
        element.checked = [element.type];
        element.nextChecked = element.next.map((im:any)=>im.type);
      });
    }else{
      gameTypeAndChannel.value.forEach((element: any) => {
        element.checked = [];
        element.nextChecked = [];
      });
    }
  }
  handleToggleReverse('camcelReverse');
}
// 反选
const handleToggleReverse = (val:any) => {
  if(val === 'camcelReverse'){
    form.value.reverse = false;
  }else{
    handleToggleAll('cancelAll');
    form.value.reverse = val;
    gameTypeAndChannel.value.forEach((element: any) => {
      element.checked = element.checked.length === 0 ? [element.type] : [];
      const filterNextChecked = element.next.filter((im:any) => element.nextChecked.indexOf(im.type) == -1).map((im:any)=> im.type);
      element.nextChecked = filterNextChecked;
    });
  }
}

// 切换选择框
const handleChecked = (val:any, type: string, item: any) => {
  if(type === 'item'){
    if(val.length !== 0){
      item.nextChecked = item.next.map((im:any)=>im.type);
    }else{
      item.nextChecked = [];
    }
  }
}

const getCurrentGameTypeSelected = () => {
  form.value.gameType = gameTypeAndChannel.value.reduce((im:any, next: any)=> [...im, ...next.checked], []).join(',');
  form.value.gameChannel = gameTypeAndChannel.value.reduce((im:any, next: any)=> [...im, ...next.nextChecked], []).join(',');
  dialogConfig.value.show = false;
  getUserBetInfo();
}

// 打开选择类型
const openSelector = () => {
  dialogConfig.value.show = true;
  dialogConfig.value.width = 900;
  dialogConfig.value.title = t('BetRecord.TypeSelection');
}
</script>

<style lang="scss" scoped>
@import url('./index.scss');
.games-type-selector{
  padding: var(--rem-28);
  .games-type-selector-header{
    padding: 0 var(--rem-20);
  }
  .games-type-selector-main{
    background-color: var(--z-bg-def);
    border-radius: var(--rem-20);
    padding: var(--rem-20);
    margin-top: var(--rem-10);
    .games-type-selector-list{
      display: flex;
      border-bottom: var(--rem-2) solid var(--border-table-line);
      padding: var(--rem-10) 0;
      .games-type-selector-list__left{
        width: var(--rem-180);
        box-sizing: border-box;
        border-right: var(--rem-2) solid var(--border-table-line);
        margin-right: var(--rem-20);
      }
      .games-type-selector-list__right{
        width: calc(100% - var(--rem-180));
      }
    }
  }
  .games-type-selector-btn{
    width: var(--rem-400);
    display: block;
    margin: var(--rem-50) auto 0;
  }
}
</style>
